/**
 * Created by w2ex on 09/11/2016.
 * @description api mixin
 */
import apiurl from '../config/apiurl'
const ERROR_HANDLER = {
    '401': res => {
        // need oauth (wechat)
        location.href = res.resultData;
    },
    '420': res => {
        mui.toast('请求参数不正确')
    },
    '500': res => {
        mui.toast('服务器内部错误')
    },
    '911': res => {
        mui.toast('当前存在未关闭的会话')
    },
    '912': res => {
        mui.toast('当前客服状态为离开或忙碌')
    }
}

const resolveError = (res) => {
    if (res.code in ERROR_HANDLER) {
        ERROR_HANDLER[res.code].call(null, res);
        return
    }
    //default errorHandler
    mui.toast(res.resultMsg)
}

const resolveResult = (res, success, error) => {
    res = res.json()
    if (res.result) {
        success(res)
    } else {
        if (!error(res)) {
            resolveError(res)
        }
    }
}

const handleNetworkError = (res) => {
    mui.toast('网络错误: ' + res.statusText)
}

export default {
    methods: {
        getJSON(api, query, success = () => false, error = () => false) {
            this.$http.get(apiurl[api](query), {
                params: query,
                credentials: true   //cross domain
            }).then(res => {
                resolveResult(res, success, error)
            }, res => {
                handleNetworkError(res)
            })
        },
        post(api, data,success = () => false, error = () => false) {
            this.$http.post(apiurl[api](), data, {
                credentials: true   //cross domain
            }).then(res => {
                resolveResult(res, success, error)
            }, res => {
                handleNetworkError(res)
            })
        }
    }
}
